import logging
import typing

from PSData import PSData
from PySide6.QtWidgets import QWidget

from WidgetFactory.WFactory import WFactory

from .TestWidgets import TWDataUpdateList


class WidgetFactory(WFactory):
    def __init__(self) -> None:
        super().__init__()
        self.PsServerEnable(0x0002, 0x01)
        self._nameMapWidget['TWDataUpdateList'] = TWDataUpdateList

    def PsGetDataSync(self, data: 'PSData') -> typing.Union['PSData', None]:
        if (data.header == 'GetWidgetList'):
            data.value = self._GetWidgetList()
            return data
        elif (data.header == 'CreateWidgetByStr'):
            if data.args in self._nameMapWidget.keys():
                widget_ = self._CreateWidgetByStr(data.args)
                if (isinstance(widget_, QWidget)):
                    data.value = widget_
                    return data
                return None
            else:
                logging.error('Can\'t find widget named {0} in Widget Factory'.format(data.args))
                return None
        return None

    def PsSetDataSync(self, data: 'PSData') -> 'bool':
        print('WidgetFacoty 收到了来自其他服务的数据')
        print(data.header)
        print(data.value)
        return True


    
    def _CreateWidgetByStr(self, name: 'str') -> typing.Union['QWidget', None]:
        '''
        Funtion: 
            通过字符串来获取Widget
        args:
            name: 'str' 希望创建的窗体名字
        return:
            如果本Factory创建期望的窗体成功，就返回 True
            否则返回 False
        '''
        wid_ = self._nameMapWidget.get(name, None)
        try:
            wid_ = wid_()
        except:
            logging.error('Can\'t create widget by name {0}'.format(name))
        if isinstance(wid_, QWidget):
            return wid_
        return None
